﻿using System;
using System.Linq;
using System.Collections.Generic;
using DataAccess.Common;
using BusinessCommon.DTO;
using BusinessCommon.Utilities;
using System.Data.Objects;
using System.Data;

namespace DataAccess.Implementation
{
    /// <summary>
    /// 
    /// </summary>
    public class UserLogin : IUserLogin
    {

        /// <summary>
        /// Lấy thông tin đăng nhập của user
        /// </summary>
        /// <param name="userName">Username</param>
        /// <param name="passWord">Password</param>
        /// <returns>UserDto: Thông tin của user</returns>
        public UserDto GetUserLogin(string userName, string passWord)
        {
            using (var context = DbConectionFactories.CreateContext())
            {
                var user = (from tantou in context.TANTOU_MST
                            where tantou.TANTOU_ID.Equals(userName)
                             && tantou.TAN_PWORD.Equals(passWord)
                             && tantou.START_DATE <= DateTime.Now
                             && (tantou.END_DATE == null || tantou.END_DATE >= DateTime.Now)
                             && tantou.ENT_KBN.Equals(ItemDefineIF.ENT_KBN_USE)
                            select new UserDto
                            {
                                Password = tantou.TAN_PWORD,
                                User_ID = tantou.TANTOU_ID,
                                Role = tantou.TAN_ROLE,
                                Name = tantou.TAN_NAME,
                                Change_PWTime = tantou.TAN_CHANGE_PWDATE
                            })
                    .FirstOrDefault();
                return user;
            }
        }

        /// <summary>
        /// Insert login log
        /// </summary>
        /// <param name="login_log_tbl">login_log_tbl</param>
        /// <returns>True: Success, False: Fail</returns>
        public bool InsertLoginLog(LOGIN_LOG_TBL login_log_tbl)
        {
            using (var context = DbConectionFactories.CreateContext())
            {
                context.AddToLOGIN_LOG_TBL(login_log_tbl);
                context.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// Insert login log
        /// </summary>
        /// <param name="tantou_mst">tantou_mst</param>
        /// <returns>True: Success, False: Fail</returns>
        public void UpdatePassWord(TANTOU_MST tantou_mst)
        {
            using (var context = DbConectionFactories.CreateContext())
            {
                context.TANTOU_MST.Attach(tantou_mst);
                context.ObjectStateManager.ChangeObjectState(tantou_mst, System.Data.EntityState.Modified);
                context.SaveChanges();
            }
        }

        public List<UserDto> GetUserTest()
        {
            throw new NotImplementedException();
        }
    }
}
